/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.common.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import ssn.common.view.AjaxFileView;
import ssn.common.view.DownloadView;
import ssn.common.vo.FileVO;

/**  
 * @Class Name : 
 * @Description : 
 * @Modification Information  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2013.10.05           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@Controller
public class FileUploadController extends CommonController {
	
	@Resource(name="common.ajaxFileView")
	private AjaxFileView ajaxFileView;

	@RequestMapping("/fileUpload.do")
	public ModelAndView fileUpload(@ModelAttribute("fileVO") FileVO fileVO) throws IOException{
		
		ModelAndView mav = new ModelAndView(ajaxFileView);
		MultipartFile file = fileVO.getFile();

		String tempPath = propertiesService.getString("file.temp.path");
		String tempUrl = propertiesService.getString("file.temp.url");
		UUID uuid = UUID.randomUUID();
		String savaPath = "";
		
		fileVO.setOriFileName(file.getOriginalFilename());
		fileVO.setSaveFileName(uuid.toString());
		fileVO.setFileSize(file.getSize());
		
		File makeDir = new File(tempPath);
		if (!makeDir.exists()) {
			makeDir.mkdirs();
		}
		
		savaPath = tempPath + File.separator + fileVO.getSaveFileName() + fileVO.getFileExt();
		
		if(fileVO.getFileSize() > 0){
			InputStream is = file.getInputStream();
			OutputStream os = new FileOutputStream(savaPath);
			int read = 0;
			byte[] bytes = new byte[8192];
			while ((read = is.read(bytes, 0, 8192)) != -1) {
				os.write(bytes, 0, read);
			}
			os.close();
			is.close();
			fileVO.setTempFullUrl(servletContext.getContextPath()+tempUrl+"/"+fileVO.getSaveFileName() + fileVO.getFileExt());
			mav.addObject("fileVO",fileVO);
		}else{
			mav.addObject("fileVO",null);
		}
		return mav;
	}
}
